package com.itheima.tanhua.dubbo.mongo.api.impl;

import com.itheima.tanhua.mongo.Friend;
import com.itheima.tanhua.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lff
 * @date 2022/3/26
 */
@Component
public class PublisherApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //标识这个方法放到一个新的线程中运行
    @Async
    public void publisher(ObjectId movementId, Long uid) {
        // 2. 根据当前用户查询friend表
        Criteria criteria = Criteria.where("userId").is(uid);
        //查询
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        // 3. 添加数据到 movenment_timeline
        //填充mvenment_timeline
        List<MovementTimeLine> movementTimeLines = friends.stream().map(friend -> {
            MovementTimeLine m = new MovementTimeLine();
            m.setCreated(System.currentTimeMillis());
            //设置朋友的id
            m.setFriendId(friend.getFriendId());
            //设置所属用户的id
            m.setUserId(uid);
            //设置动态id
            m.setMovementId(movementId);
            return m;
        }).collect(Collectors.toList());
        //批量添加
        mongoTemplate.insert(movementTimeLines, MovementTimeLine.class);
    }
}
